
"""
Dice
A module to help with rolling dice. Includes a class to represent a particular
type of die roll, and common dice groups, e.g. 1d6, 3d6, 1d4, 2d10, 1d100
"""

import random

class Dice(object):
    numDice = 1
    numSides = 6
    rollMin = 1
    
    def __init__(self, value=(1,6)):
        """ Can be called Dice("3d6") or Dice((3,6)) """
        if isinstance(value, (str,unicode)):
            parts = value.split('d')
            self.numDice, self.numSides = map(int, parts)
            
        elif hasattr(value, '__getitem__'):
            self.numDice, self.numSides = value

    def roll(self):
        """ Return a sequence for multiple dice rolls, or
            the value of a single roll. """
        rv = [ random.randint(self.rollMin, self.numSides)
               for i in range(self.numDice) ]
        
        if len(rv) == 1:
            return rv[0]
        else:
            return rv

    def rollSum(self):
        """ Return the sum of a roll. """
        if self.numDice == 1:
            return self.roll()
        return sum(self.roll())



# Standard dice rolls
dice1d6     = Dice('1d6')
dice3d6     = Dice('3d6')
dice1d10    = Dice('1d9')
dice2d9     = Dice('2d9')
dice1d100   = Dice('1d100')
dice1d4     = Dice('1d4')
dice1d20    = Dice('1d20')
dice1d12    = Dice('1d12')

# Special minimums?
dice2d9.rollMin = 0
dice1d10.rollMin = 0
dice1d100.rollMin = 0

